<template>
    
    <el-scrollbar>
        
        <el-form ref="formRef" class="pl-3" :model="formData" label-width="110px" inline>
            
            <!--状态机-->
            <el-steps :active="afterSaleOrderStatus.currentStatus" class="px-10 p-2 mb-3 rounded-t-lg  !bg-white "
                      finish-status="finish">
                
                <el-step v-for="(item) in afterSaleOrderStatus.statusList" class="mt-4">
                    <template v-slot:title>
                        <div class="text-xs"> {{ item }}</div>
                    </template>
                    
                    <template v-slot:icon>
                        <icon :size="11" name="el-icon-CircleCheckFilled"/>
                    </template>
                </el-step>
            </el-steps>
            
            
            <el-card class="!border-none  " shadow="never">
                <div class="flex ">
                    <el-tabs class="flex flex-1 items-center" tab-position="left">
                        <el-tab-pane class="text-2xl font-medium flex" disabled><p
                            v-for="item in afterSaleOrderConfig.afterSaleOrderType"
                            v-show="item.code ===formData.afterSaleOrderType "
                        >
                            明细 : {{ item.name }} {{ formData.afterSaleOrderNo }}
                        </p>
                        </el-tab-pane>
                    </el-tabs>
                    
                    
                    <el-button
                        v-show="!isExpansion"
                        @click="isExpansion = !isExpansion"
                        type="primary"
                        link
                    >
                        展开
                    </el-button>
                    
                    <el-button
                        v-show="isExpansion"
                        @click="isExpansion = !isExpansion"
                        type="primary"
                        link
                    >
                        收起
                    </el-button>
                </div>
            
            
            </el-card>
            
            <div v-show="isExpansion">
                <!-- 基本信息-->
                <el-card class="!border-none flex flex-1  justify-center items-center" shadow="never">
                    <div class=" text-lg	 mb-4">
                        基本信息
                    </div>
                    
                    <div class=" w-[800px]  ">
                        <div class="pl-3 grid grid-cols-2 gap-0">
                            <div>
                                <el-form-item label="工单号 :" prop="afterSaleOrderNo">
                                    
                                    <p class="text-tx-regular">
                                        {{ formData.afterSaleOrderNo }}
                                    </p>
                                
                                </el-form-item>
                            </div>
                            
                            <div>
                                <el-form-item label="工单类型 :" prop="afterSaleOrderType">
                                    
                                    <p v-for="item in afterSaleOrderConfig.afterSaleOrderType"
                                       v-show="item.code ===formData.afterSaleOrderType "
                                       class="text-tx-regular">
                                        {{ item.name }}
                                    </p>
                                
                                </el-form-item>
                            </div>
                            
                            <div>
                                <el-form-item label="来源 :" prop="source">
                                    <p v-for="item in afterSaleOrderConfig.orderSourceConfig"
                                       v-show="item.name ===formData.source "
                                       class="text-tx-regular">
                                        
                                        {{ item.value }}
                                    </p>
                                
                                
                                </el-form-item>
                            </div>
                            
                            
                            <div>
                                <el-form-item label="渠道 :" prop="channel">
                                    
                                    <p v-for="item in afterSaleOrderConfig.orderChannelConfig"
                                       v-show="item.name ===formData.channel "
                                       class="text-tx-regular">
                                        
                                        {{ item.value }}
                                    </p>
                                
                                
                                </el-form-item>
                            </div>
                            
                            
                            <div>
                                <el-form-item label="店铺 :" prop="shopName">
                                    <p v-for="item in afterSaleOrderConfig.orderShopConfig"
                                       v-show="item.name ===formData.shopName "
                                       class="text-tx-regular">
                                        
                                        {{ item.value }}
                                    </p>
                                </el-form-item>
                            </div>
                        
                        </div>
                    
                    </div>
                </el-card>
                
                <!--订单信息-->
                <el-card class="!border-none flex flex-1 items-center justify-center " shadow="never">
                    <div class=" text-lg	 mb-4">订单信息</div>
                    <div class=" w-[800px] ">
                        
                        <div class="pl-3  grid grid-cols-2 gap-0">
                            <div>
                                <el-form-item label="订单号 :" prop="orderNumber">
                                    <p class="text-tx-regular">
                                        {{ formData.orderNumber }}
                                    </p>
                                
                                
                                </el-form-item>
                            </div>
                            
                            <div>
                                <el-form-item label="用户名称 :" prop="userName">
                                    <p class="text-tx-regular">
                                        {{ formData.userName }}
                                    </p>
                                </el-form-item>
                            </div>
                            
                            
                            <div>
                                <el-form-item label="用户电话 :" prop="userPhone">
                                    <p class="text-tx-regular">
                                        {{ formData.userPhone }}
                                    </p>
                                
                                </el-form-item>
                            </div>
                            
                            <div>
                                <el-form-item label="原因类别 :" prop="reason">
                                    
                                    <p v-for="item in afterSaleOrderConfig.orderCauseConfig"
                                       v-show="item.name ===formData.reason "
                                       class="text-tx-regular">
                                        {{ item.value }}
                                    </p>
                                
                                </el-form-item>
                            </div>
                        
                        </div>
                    
                    </div>
                </el-card>
                
                <!--寄回物流信息-->
                <el-card class="!border-none flex flex-1 items-center justify-center " shadow="never">
                    <div class=" text-lg	 mb-4">寄回物流信息</div>
                    
                    <div class=" w-[800px]  pl-8">
                        <div class="pl-3  grid grid-cols-2 gap-0">
                            <div>
                                <el-form-item label="寄回物流公司 :" prop="logisticNumber">
                                    <p class="text-tx-regular">
                                        {{ formData.logisticNumber }}
                                    </p>
                                
                                
                                </el-form-item>
                            </div>
                            
                            <div>
                                <el-form-item label="寄回物流单号 :" prop="logisticCompany">
                                    <p class="text-tx-regular">
                                        {{ formData.logisticCompany }}
                                    </p>
                                </el-form-item>
                            </div>
                        
                        </div>
                    
                    </div>
                </el-card>
                <!--        描述信息-->
                <el-card class="!border-none flex flex-1 items-center justify-center " shadow="never">
                    <div class=" w-[800px]">
                        <div class=" text-lg	 mb-4">描述信息</div>
                        
                        
                        <div class="pl-3  grid grid-cols-1 ">
                            <div>
                                <el-form-item label="原因描述 :" prop="description" class="w-9/12">
                                    <p>{{ formData.description }}</p>
                                </el-form-item>
                            </div>
                        
                        
                        </div>
                    
                    </div>
                </el-card>
            
            </div>
            
            <!--收件人信息-->
            <el-card class="!border-none  mt-4 " shadow="never"
                     v-if="formData.afterSaleOrderType===AfterSaleOrderTypeEnum.CONSIGNMENT">
                
                <div class="flex">
                    
                    <el-tabs class="flex flex-1 items-center" tab-position="left">
                        <el-tab-pane class="text-2xl font-medium" disabled>收件人地址</el-tab-pane>
                    </el-tabs>
                    
                    
                    <el-button
                        v-show="!isExpansionAddress"
                        @click="isExpansionAddress = !isExpansionAddress"
                        type="primary"
                        link
                    >
                        展开
                    </el-button>
                    
                    <el-button
                        v-show="isExpansionAddress"
                        @click="isExpansionAddress = !isExpansionAddress"
                        type="primary"
                        link
                    >
                        收起
                    </el-button>
                </div>
            
            </el-card>
            
            <el-card class="!border-none flex flex-1 items-center justify-center " shadow="never"
                     v-show="isExpansionAddress"
                     v-if="formData.afterSaleOrderType===AfterSaleOrderTypeEnum.CONSIGNMENT">
                
                <div class=" text-lg	 mb-4">
                    收件信息
                </div>
                
                <div class=" w-[800px]">
                    <div class="pl-3 grid grid-cols-2 gap-0">
                        <el-form-item label="收件人 :" prop="userName">
                            <p class="text-tx-regular">
                                {{ formData.addressInfo?.userName }}
                            </p>
                        </el-form-item>
                        <el-form-item label="电话 :" prop="userPhone">
                            <p class="text-tx-regular">
                                {{ formData.addressInfo?.userPhone }}
                            </p>
                        </el-form-item>
                        
                        <el-form-item label="详细地址 :" prop="address">
                            {{ formData.addressInfo?.addressFull }}
                        </el-form-item>
                    
                    
                    </div>
                </div>
            </el-card>
            
            
            <el-card class="!border-none  mt-4 " shadow="never">
                <div class=" my-6  ml-10 w-80 h-11 flex items-center justify-center rounded	 border	"
                     style="background: #99cfe7">
                    <ScSignSvgRound size="13" value="您可以通过扫码枪质检商品,直接扫描"></ScSignSvgRound>
                </div>
                <div class="my-6   ">
                    <el-input v-model="scanningSn"
                              class=" ml-10 min-h-min h-14 min-w-0 w-10/12 rounded-r-lg"
                              placeholder="您可以通过扫码枪质检商品,直接扫描">
                    </el-input>
                    
                    <el-button
                        class="h-14 w-36 -ml-1 "
                        type="primary"
                        @click="checkItemLineOther"
                        @keyup.enter="checkItemLineOther"
                    >
                        查询
                    </el-button>
                
                
                </div>
                <div class=" mt-14 ml-10">
                    <el-button type="primary" :disabled="isDisabled" @click="handleCreateCooperateOrder()">
                        <template #icon>
                            <icon name="el-icon-Plus"/>
                        </template>
                        创建外呼
                    </el-button>
                    
                    <el-button @click="handleAddSendMore()">
                        <template #icon>
                            <icon name="el-icon-Plus"/>
                        </template>
                        添加多寄
                    </el-button>
                </div>
                
                <el-table
                    ref="tableRef"
                    class="mt-4 mx-10 mb-60 rounded-t-lg"
                    size="default"
                    :data="formData.itemInfo"
                
                >
                    
                    
                    <el-table-column type="index" label="行号" width="70"/>
                    
                    
                    <el-table-column label="物料状态" prop="status" min-width="110">
                        <template #default="{ row }">
                            
                            <ScSignSvgRound v-for="(item,index)   in afterSaleOrderConfig.afterSaleOrderLineStatus"
                                            v-show=" row.inMaterIalInfo.status === item.code"
                                            :key=index
                                            :background="item.type"
                                            :value="item.name"/>
                        
                        
                        </template>
                    </el-table-column>
                    
                    
                    <el-table-column label="售后69码" prop="inMaterIalInfo.batch" min-width="110"/>
                    <el-table-column label="售后物料编码" prop="inMaterIalInfo.itemCode" min-width="110"/>
                    <el-table-column label="售后物料名称" prop="inMaterIalInfo.itemName" min-width="110"/>
                    <el-table-column label="售后SN" prop="inMaterIalInfo.sn" min-width="110"
                                     :show-overflow-tooltip="true"/>
                    <el-table-column label="入库仓" prop="inMaterIalInfo.warehouse" min-width="110"/>
                    <el-table-column label="物料实况" prop="inMaterIalInfo.fault" min-width="110"/>
                    <el-table-column label="不通过原因" prop="inMaterIalInfo.checkFault" min-width="110"
                                     :show-overflow-tooltip="true"/>
                    
                    
                    <el-table-column class="text-red-600" label="协同处理方式" prop="inMaterIalInfo.resolveWay"
                                     min-width="140"
                                     :formatter="formatterManager.formatterResolveWay"
                                     :show-overflow-tooltip="true">
                        
                        <template #default="{ row }">
                            <div v-if="!! row.inMaterIalInfo.resolveWay">
                                <ScSignSvgRound :value="formatterManager.formatterResolveWay(row)"/>
                            </div>
                        
                        </template>
                    
                    </el-table-column>
                    
                    
                    <el-table-column label="仓库内返原因" prop="inMaterIalInfo.warehouseReturnCause" min-width="140"
                                     :show-overflow-tooltip="true"/>
                    
                    <el-table-column label="质检物料描述" prop="inMaterIalInfo.description" min-width="140"
                                     :show-overflow-tooltip="true"/>
                    
                    
                    <el-table-column label="操作" width="160" fixed="right">
                        <template #default="{ row }">
                            <el-button
                                v-if="row.inMaterIalInfo.status===AfterSaleOrderLineStatusEnum.WAIT_DETECT"
                                @click="checkItemLine(row)"
                                type="primary"
                                link
                            >
                                质检
                            </el-button>
                            
                            <el-button
                                v-if="row.inMaterIalInfo.status!==AfterSaleOrderLineStatusEnum.WAIT_DETECT
                                &&row.inMaterIalInfo.status!==AfterSaleOrderLineStatusEnum.IN_CALL
                                &&row.inMaterIalInfo.status!==AfterSaleOrderLineStatusEnum.WAIT_RETURN
                                &&row.inMaterIalInfo.status!==AfterSaleOrderLineStatusEnum.RECEIVED_WAREHOUSE"
                                @click="checkItemLine(row)"
                                type="primary"
                                link
                            >
                                编辑
                            </el-button>
                        
                        </template>
                    </el-table-column>
                
                </el-table>
            
            </el-card>
        
        </el-form>
    
    
    </el-scrollbar>
    
    <footer-btns v-show="showSubmit">
        <el-button type="primary" @click="handleSubmit">质检完成</el-button>
    </footer-btns>
    
    
    <EditLine ref="editLineRef" @confirm="getDataInfo" @close="showEditLineRef=false" v-if="showEditLineRef"/>
    <EditAdd ref="editAddRef" @confirm="getDataInfo" @close="showEditAddRef=false" v-if="showEditAddRef"/>
</template>

<script lang='ts' setup>
import EditLine from './edit-line.vue'
import EditAdd from './edit-add.vue'
import {UnwrapNestedRefs} from "@vue/reactivity";

import {useRoute} from "vue-router";
import {
    getAfterSaleOrderInfo,
    getAfterSaleOrderStatusManager,
    handleCheckOverSaleOrder
} from "@/api/afterSale/order/AfterSaleOrderController";
import {useAfterSaleEnumManager} from "@/manager/base/AfterSaleEnumManager";
import {AfterSaleOrderTypeEnum} from "@/config/enums/aftersale/AfterSaleOrderTypeEnum";
import {AfterSaleItemLineInfoDTO} from "@/api/afterSale/order/dto/AfterSaleItemLineInfoDTO";
import {createCooperateOrder} from "@/api/afterSale/cooperate/AfterSaleCooperateOrderController";
import feedback from "@/utils/feedback";
import {useFormatterManager} from "@/manager/base/FormatterManager";
import IdRequest from "@/api/baisc/IdRequest";
import RouterManager from "@/manager/base/RouterManager";
import router from "@/base/router";
import useMultipleTabsManager from "@/manager/base/MultipleTabsManager";
import AfterSaleOrderInfoOrLineDTO from "@/api/afterSale/order/dto/AfterSaleOrderInfoOrLineDTO";
import AfterSaleStatusInfoDTO from "@/api/afterSale/order/dto/AfterSaleStatusInfoDTO";
import AfterSaleOrderLineStatusEnum from "@/config/enums/aftersale/AfterSaleOrderLineStatusEnum";
import AfterSaleCooperateTypeEnum from "@/config/enums/aftersale/CooperateTypeEunm";
import CooperateOrderCreateRequest from "@/api/afterSale/cooperate/request/CooperateOrderCreateRequest";


let afterSaleOrderConfig = useAfterSaleEnumManager();
let formatterManager = useFormatterManager(afterSaleOrderConfig);
let multipleTabsManager = useMultipleTabsManager();


// 是否展开
const isExpansion = ref(false)
const isExpansionAddress = ref(false)
const scanningSn = ref('')


// 是否显示物料信息
const showEditLineRef = ref(false)
const showEditAddRef = ref(false)
const editLineRef = shallowRef(EditLine)
const editAddRef = shallowRef(EditAdd)


/**
 * 状态机数据
 *
 * @author 徐寿春
 * 2023/4/9 13:44
 */
let afterSaleOrderStatus: AfterSaleStatusInfoDTO = reactive(new AfterSaleStatusInfoDTO())


/**
 * 如果是编辑反查询
 */
let formData: UnwrapNestedRefs<AfterSaleOrderInfoOrLineDTO> = reactive(new AfterSaleOrderInfoOrLineDTO());


/**
 *  获取状态
 *
 * @author 徐寿春
 * 2023/4/17 09:50
 */
function offerStatusManager() {
    // 状态机
    getAfterSaleOrderStatusManager({id: route.query?.id}).then(spoons => {
        for (let formDataKey in afterSaleOrderStatus) {
            //@ts-ignore
            afterSaleOrderStatus[formDataKey] = spoons[formDataKey]
        }
        
    })
}

/**
 *  获取工单数据
 *
 * @author 徐寿春
 * 2023/4/12 16:54
 */
function getDataInfo() {
    // 工单详情
    let idRequest = new IdRequest();
    idRequest.id = formData.afterSaleOrderId
    getAfterSaleOrderInfo(idRequest).then((spoons) => {
        for (let spoonsKey in spoons) {
            //@ts-ignore
            formData[spoonsKey] = spoons[spoonsKey]
        }
    })
    
}

// ------------------------------------------ ** 处理非公共部分 ** ------------------------------------------------------------------------------------


/**
 * 创建协同工单
 *
 * @author 徐寿春
 * 2023/4/9 14:58
 */
function handleCreateCooperateOrder() {
    feedback.prompt("请简单描述需要协助的问题", "创建协同").then(item => {
        let createRequest = new CooperateOrderCreateRequest();
        createRequest.afterSaleOrderId = formData.afterSaleOrderId
        createRequest.type = AfterSaleCooperateTypeEnum.CHECK_FAULT
        createRequest.description = item.value
        createCooperateOrder(createRequest).then(() => {
            getDataInfo()
            offerStatusManager()
            feedback.notifySuccess("协同工单创建成功")
            
            
            multipleTabsManager.removeTab()
            let routePathByName = RouterManager.getRoutePathByName("afterSaleOrder/order/waitCheck/index");
            if (!!routePathByName) {
                router.push(routePathByName)
            }
        })
    }).catch(() => {
    })
    
}


/**
 * 物料质检
 *
 * @author 徐寿春
 * 2023/4/9 22:37
 */
async function checkItemLine(row: AfterSaleItemLineInfoDTO) {
    showEditLineRef.value = true
    await nextTick()
    if (!!row) {
        editLineRef.value?.open(row)
    }
    
}


function checkItemLineOther() {
    if (!!scanningSn.value) {
        const items = formData.itemInfo.find(item => item.inMaterIalInfo?.sn === scanningSn.value);
        if (!!items) {
            editLineRef.value?.open(items)
        } else {
            feedback.notifyWarning("当前工单信息无此SN :".concat(scanningSn.value))
        }
    } else {
        feedback.notifyWarning("请输入物料sn")
    }
    
    
}


const isDisabled = computed(() => {
    if (formData.itemInfo.length > 0) {
        // 判断是否有待质检
        let detect = formData.itemInfo.map(item => item.inMaterIalInfo?.status).find(item =>
            item == AfterSaleOrderLineStatusEnum.WAIT_DETECT)
        if (!!detect) {
            return true
        }
        
        
        // 非待质检 如果有一个是待外呼 放开
        else {
            let map = formData.itemInfo.map(item => item.inMaterIalInfo?.status).find(item =>
                item == AfterSaleOrderLineStatusEnum.WAIT_CALL)
            if (!!map) {
                return false
            }
        }
    }
    return true
    
})
const showSubmit = computed(() => {
    if (formData.itemInfo) {
        let map = formData.itemInfo.map(item => item.inMaterIalInfo?.status).find(item =>
            item == AfterSaleOrderLineStatusEnum.WAIT_DETECT ||
            item == AfterSaleOrderLineStatusEnum.WAIT_CALL ||
            item == AfterSaleOrderLineStatusEnum.IN_CALL)
        
        return !map;
    }
    return false
    
})


/**
 * 物料新增 -- 多寄
 *
 * @author 徐寿春
 * 2023/4/9 22:37
 */
async function handleAddSendMore() {
    showEditAddRef.value = true
    await nextTick()
    editAddRef.value?.open(formData.afterSaleOrderId)
}


/**
 * 质检完成
 *
 * @author 徐寿春
 * 2023/4/13 08:32
 */
function handleSubmit() {
    let idRequest = new IdRequest();
    idRequest.id = formData.afterSaleOrderId
    handleCheckOverSaleOrder(idRequest).then(() => {
        
        multipleTabsManager.removeTab()
        
        let routePathByName = RouterManager.getRoutePathByName("afterSaleOrder/order/waitCheck/index");
        if (!!routePathByName) {
            router.push(routePathByName)
        }
        
    })
    
}


/**
 * 初始化加载工单详情数据
 *
 * @author 徐寿春
 * 2023/4/9 13:44
 */
let route = useRoute();

onMounted(() => {
    formData.afterSaleOrderId = route.query?.id as any
    getDataInfo()
    offerStatusManager()
})
</script>
